package org.ptkparty.client.view.profil;

import java.util.List;

import org.ptkparty.client.Context;
import org.ptkparty.client.activity.ProfilActivity;
import org.ptkparty.client.place.PlayerDto;
import org.ptkparty.client.resources.CellTableResource;
import org.ptkparty.client.resources.Resources;
import org.ptkparty.client.view.players.PlayerCell;
import org.ptkparty.shared.cons.GoogleApiConst;
import org.ptkparty.shared.dto.ResultDto;

import com.google.api.gwt.oauth2.client.Auth;
import com.google.api.gwt.oauth2.client.AuthRequest;
import com.google.gwt.cell.client.SafeHtmlCell;
import com.google.gwt.core.client.Callback;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.AnchorElement;
import com.google.gwt.dom.client.DivElement;
import com.google.gwt.editor.client.Editor;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.safehtml.shared.SafeHtml;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.InlineLabel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.Widget;
import com.google.gwt.view.client.ListDataProvider;
import com.google.gwt.view.client.SelectionChangeEvent;
import com.google.gwt.view.client.SingleSelectionModel;
import com.google.gwt.visualization.client.AbstractDataTable.ColumnType;
import com.google.gwt.visualization.client.DataTable;
import com.google.gwt.visualization.client.LegendPosition;
import com.google.gwt.visualization.client.visualizations.LineChart;
import com.google.gwt.visualization.client.visualizations.LineChart.Options;
import com.google.gwt.visualization.client.visualizations.PieChart;

public class ProfilView extends Composite implements Editor<PlayerDto> {

	private static ProfilViewUiBinder uiBinder = GWT.create(ProfilViewUiBinder.class);

	interface ProfilViewUiBinder extends UiBinder<Widget, ProfilView> {
	}

	private ProfilActivity activity;

	private NumberFormat percentFormat = NumberFormat.getFormat("##0");

	@UiField
	HTMLPanel mainPanel;

	@UiField
	@Path("nickname")
	Label nicknameLb;

	@UiField
	@Path("email")
	InlineLabel emailLb;

	@UiField
	Image imageImg;

	@UiField
	DivElement plusOneGplusDiv;

	@UiField
	DivElement fbLikeDiv;

	@UiField
	HTMLPanel scoreStats;

	@UiField
	AnchorElement logout;

	@UiField
	@Ignore
	InlineLabel championshipName, nbPointsChampionship, nbWins, nbLoses, nbWinFannys, nbLoseFannys, nbMathsChampionship;

	@UiField
	HTMLPanel championshipStats;

	@UiField(provided = true)
	CellTable<ResultDto> topChampionshipResult;

	@UiField(provided = true)
	CellTable<ResultDto> topWinner;

	@UiField(provided = true)
	CellTable<ResultDto> topLooser;

	@UiField(provided = true)
	CellTable<ResultDto> topKiller;

	@UiField(provided = true)
	CellTable<ResultDto> topVictim;

	public ProfilView() {
		final SingleSelectionModel<ResultDto> sm = new SingleSelectionModel<ResultDto>();
		sm.addSelectionChangeHandler(new SelectionChangeEvent.Handler() {

			@Override
			public void onSelectionChange(SelectionChangeEvent event) {
				activity.playerSelected(sm.getSelectedObject().getUserId());
			}
		});

		// Top champions table init
		topChampionshipResult = new CellTable<ResultDto>(Integer.MAX_VALUE, CellTableResource.INSTANCE);
		topChampionshipResult.setSelectionModel(sm);
		topChampionshipResult.addColumn(new Column<ResultDto, SafeHtml>(new SafeHtmlCell()) {

			@Override
			public SafeHtml getValue(ResultDto object) {
				SafeHtmlBuilder sb = new SafeHtmlBuilder();
				if (object.getUserImage() != null) {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUserImage(), object.getUser(), " (" + object.getPoints() + " points)"));
				} else {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUser(), " (" + object.getPoints() + " points)"));
				}
				return sb.toSafeHtml();
			}
		}, SafeHtmlUtils.fromTrustedString("<i class='icon-star'></i>&nbsp;Top joueurs"));

		// Best partners
		topWinner = new CellTable<ResultDto>(Integer.MAX_VALUE, CellTableResource.INSTANCE);
		topWinner.setSelectionModel(sm);
		topWinner.addColumn(new Column<ResultDto, SafeHtml>(new SafeHtmlCell()) {

			@Override
			public SafeHtml getValue(ResultDto object) {
				SafeHtmlBuilder sb = new SafeHtmlBuilder();
				if (object.getUserImage() != null) {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUserImage(), object.getUser(), "(" + percentFormat.format(object.getPoints()) + " % victoire)"));
				} else {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUser(), "(" + percentFormat.format(object.getPoints()) + " % victoire)"));
				}
				return sb.toSafeHtml();
			}
		}, SafeHtmlUtils.fromTrustedString("<i class='icon-thumbs-up'></i>&nbsp;Meilleurs partenaires"));

		// Worth partners
		topLooser = new CellTable<ResultDto>(Integer.MAX_VALUE, CellTableResource.INSTANCE);
		topLooser.setSelectionModel(sm);
		topLooser.addColumn(new Column<ResultDto, SafeHtml>(new SafeHtmlCell()) {

			@Override
			public SafeHtml getValue(ResultDto object) {
				SafeHtmlBuilder sb = new SafeHtmlBuilder();
				if (object.getUserImage() != null) {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUserImage(), object.getUser(), " (" + (percentFormat.format(100 - object.getPoints())) + " % défaite)"));
				} else {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUser(), " (" + (percentFormat.format(100 - object.getPoints())) + " % défaite)"));
				}
				return sb.toSafeHtml();
			}
		}, SafeHtmlUtils.fromTrustedString("<i class='icon-thumbs-down'></i>&nbsp;Pires partenaires"));

		topKiller = new CellTable<ResultDto>(Integer.MAX_VALUE, CellTableResource.INSTANCE);
		topKiller.setSelectionModel(sm);
		topKiller.addColumn(new Column<ResultDto, SafeHtml>(new SafeHtmlCell()) {

			@Override
			public SafeHtml getValue(ResultDto object) {
				SafeHtmlBuilder sb = new SafeHtmlBuilder();
				if (object.getUserImage() != null) {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUserImage(), object.getUser(), " (" + object.getLooseGames() + " défaites)"));
				} else {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUser(), " (" + object.getLooseGames() + " défaites)"));
				}
				return sb.toSafeHtml();
			}
		}, SafeHtmlUtils.fromTrustedString("<i class='icon-screenshot'></i>&nbsp;Top killer"));

		topVictim = new CellTable<ResultDto>(Integer.MAX_VALUE, CellTableResource.INSTANCE);
		topVictim.setSelectionModel(sm);
		topVictim.addColumn(new Column<ResultDto, SafeHtml>(new SafeHtmlCell()) {

			@Override
			public SafeHtml getValue(ResultDto object) {
				SafeHtmlBuilder sb = new SafeHtmlBuilder();
				if (object.getUserImage() != null) {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUserImage(), object.getUser(), " (" + object.getWinGames() + " victoires)"));
				} else {
					sb.append(PlayerCell.template.playerTemplateWithData(object.getUser(), " (" + object.getWinGames() + " victoires)"));
				}
				return sb.toSafeHtml();
			}
		}, SafeHtmlUtils.fromTrustedString("<i class='icon-ambulance'></i>&nbsp;Top victimes"));

		// Init this widget
		initWidget(uiBinder.createAndBindUi(this));

		// Authentication request
		AuthRequest req = new AuthRequest(GoogleApiConst.GPLUS_AUTH_URL, GoogleApiConst.GPLUS_CLIENT_ID).withScopes(GoogleApiConst.GPLUS_SCOPE);
		Auth.get().login(req, new Callback<String, Throwable>() {

			@Override
			public void onSuccess(String result) {
				activity.connectOnGooglePlus(result);
			}

			@Override
			public void onFailure(Throwable reason) {

			}
		});

		// Set social buttons (G+ & FB)
		plusOneGplusDiv.setInnerHTML("<g:plusone annotation=\"none\" width=\"300\" href=\"" + Window.Location.getHref() + "\"></g:plusone>");
		// fbLikeDiv.setInnerHTML("<fb:like href=\"" + Window.Location.getHref() + "\" send=\"false\" layout=\"box_count\" width=\"450\" show_faces=\"false\"></fb:like>");
	}

	public void setPresenter(ProfilActivity profilActivity) {
		activity = profilActivity;
	}

	public void setImages(String image, String cover) {
		// Set the google plus avatar image
		if (image != null) {
			imageImg.setUrl(image);
		} else {
			imageImg.setResource(Resources.resources.getEmptyAvatar80px());
			imageImg.setStyleName("profil-img");
			imageImg.addStyleName("pull-left");
		}
		// set the google plus cover
		if (cover != null) {
			mainPanel.getElement().setAttribute("style", "background: #EEE url(" + cover.toString() + ") no-repeat ;background-size: cover;");
		}
	}

	public void buildScoreStats(List<ResultDto> response) {
		DataTable data = DataTable.create();
		data.addColumn(ColumnType.NUMBER);
		data.addRows(response.size());

		for (int i = 0; i < response.size(); i++) {
			data.setValue(i, 0, response.get(i).getPoints());
		}

		Options options = Options.create();
		options.setWidth(scoreStats.getOffsetWidth());
		options.setHeight(250);
		options.setTitle("Evolution du score");
		options.setEnableTooltip(true);
		options.setLegend(LegendPosition.NONE);
		options.setBackgroundColor("transparent");
		options.setTitleColor("white");
		options.setAxisColor("white");
		options.setSmoothLine(true);

		LineChart lineChart = new LineChart(data, options);
		scoreStats.add(lineChart);

		// Build championship stats from last result
		if (!response.isEmpty()) {
			buildChampionshipStats(response.get(response.size() - 1));
		}
	}

	public void buildChampionshipStats(ResultDto resultDto) {
		// Add championship stats
		championshipName.setText(Context.get().getCurrentChampionshipProxy().getName());
		nbPointsChampionship.setText(String.valueOf(resultDto.getPoints()));
		nbMathsChampionship.setText(String.valueOf(resultDto.getGameNumber()));
		nbWins.setText(String.valueOf(resultDto.getWinGames()));
		nbLoses.setText(String.valueOf(resultDto.getLooseGames()));
		nbWinFannys.setText(String.valueOf(resultDto.getFannyWinGames()));
		nbLoseFannys.setText(String.valueOf(resultDto.getFannyLooseGames()));

		// Build the pie chart
		DataTable data = DataTable.create();
		data.addColumn(ColumnType.STRING, "Type");
		data.addColumn(ColumnType.NUMBER, "Nombre");
		data.addRows(4);

		data.setValue(0, 0, "Victoires");
		data.setValue(0, 1, resultDto.getWinGames() - resultDto.getFannyWinGames());
		data.setValue(1, 0, "Défaites");
		data.setValue(1, 1, resultDto.getLooseGames() - resultDto.getFannyLooseGames());
		data.setValue(2, 0, "Fanny gagnés");
		data.setValue(2, 1, resultDto.getFannyWinGames());
		data.setValue(3, 0, "Fanny encaissés");
		data.setValue(3, 1, resultDto.getFannyLooseGames());

		PieChart.Options options = PieChart.Options.create();
		options.setTitle("Résumé du championnat");
		options.setEnableTooltip(true);
		options.setBackgroundColor("transparent");
		options.setLegend(LegendPosition.NONE);
		options.set3D(true);
		options.setHeight(230);
		options.setTitleColor("white");

		PieChart pieChart = new PieChart(data, options);
		championshipStats.add(pieChart);
	}

	public void showTopResult(List<ResultDto> topChampionshipResult) {
		if (topChampionshipResult != null) {
			// Fill the top result tab
			new ListDataProvider<ResultDto>(topChampionshipResult).addDataDisplay(this.topChampionshipResult);
		}
	}

	public void showTopWinner(List<ResultDto> topWinner) {
		if (topWinner != null) {
			new ListDataProvider<ResultDto>(topWinner).addDataDisplay(this.topWinner);
		}
	}

	public void showTopLooser(List<ResultDto> topLooser) {
		if (topLooser != null) {
			new ListDataProvider<ResultDto>(topLooser).addDataDisplay(this.topLooser);
		}
	}

	public void setLogoutUri(String logoutUrl) {
		logout.setAttribute("href", logoutUrl);
	}

	public void showKillers(List<ResultDto> killers) {
		if (killers != null) {
			new ListDataProvider<ResultDto>(killers).addDataDisplay(this.topKiller);
		}
	}

	public void showVictims(List<ResultDto> victims) {
		if (victims != null) {
			new ListDataProvider<ResultDto>(victims).addDataDisplay(this.topVictim);
		}
	}

}
